'use strict';

const Controller = require('egg').Controller;

class RoleController extends Controller {

  async index() {
    const ctx = this.ctx;
    const { role } = ctx.service.sys;
    const data = await role.find(ctx.query);
    ctx.success({ data });
  }

  async show() {
    const ctx = this.ctx;
    const { role } = ctx.service.sys;
    const data = await role.findOne(ctx.params);
    ctx.success({ data });
  }

  async create() {
    const ctx = this.ctx;
    const { role } = ctx.service.sys;
    ctx.validate({
      name: {
        type: 'string',
        required: true,
        unique: true,
        max: 50,
        mim: 5,
      },
      identity: {
        type: 'string',
        required: true,
        unique: true,
        max: 50,
        mim: 5,
      },
      description: {
        type: 'string',
        required: true,
        unique: true,
        max: 200,
        mim: 5,
      },
      active: {
        type: 'boolean',
        required: false,
        unique: true,
      },
    });
    try {
      const id = await role.create(ctx.request.body);
      const data = {
        id,
      };
      ctx.success({ data });
    } catch (error) {
      ctx.error({ detail: error });
    }
  }

  async update() {
    const ctx = this.ctx;
    const { role } = ctx.service.sys;
    ctx.validate({
      name: {
        type: 'string',
        required: false,
        unique: true,
        max: 50,
        mim: 5,
      },
      identity: {
        type: 'string',
        required: false,
        unique: true,
        max: 50,
        mim: 5,
      },
      description: {
        type: 'string',
        required: false,
        unique: true,
        max: 200,
        mim: 5,
      },
      active: {
        type: 'boolean',
        required: false,
        unique: true,
      },
      permission: {
        type: 'array',
        required: false,
        unique: true,
      },
    });
    try {
      const params = Object.assign({ id: ctx.params.id }, ctx.request.body);
      const data = await role.update(params);
      ctx.success({ data });
    } catch (error) {
      ctx.error({ detail: error });
    }
  }

  async destroy() {
    const ctx = this.ctx;
    const { role } = ctx.service.sys;
    const data = await role.destroy(ctx.params);
    ctx.success({ data });
  }

  async setPermission() {
    const ctx = this.ctx;
    const { role } = ctx.service.sys;
    try {
      const params = Object.assign({ id: ctx.params.id }, ctx.request.body);
      const data = await role.update(params);
      ctx.success({ data });
    } catch (error) {
      ctx.error({ detail: error });
    }
  }
}

module.exports = RoleController;
